<template>
  <div class="file-preview-container">
    <div class="preview-header">
      <h2>{{ fileName }}</h2>
      <div class="preview-actions">
        <button @click="downloadFile" class="btn-download">下载</button>
        <button @click="closePreview" class="btn-close">关闭</button>
      </div>
    </div>
    
    <div class="preview-content">
      <!-- PDF预览 -->
      <iframe 
        v-if="isPdf" 
        :src="previewUrl" 
        class="preview-iframe"
        frameborder="0"
      ></iframe>
      
      <!-- 图片预览 -->
      <img 
        v-else-if="isImage" 
        :src="previewUrl" 
        class="preview-image"
        alt="预览图片"
      />
      
      <!-- Office文档预览（使用Office Online Viewer或直接iframe） -->
      <div v-else-if="isOfficeDoc" class="office-preview-container">
        <div class="office-preview-info">
          <p>Office文档预览</p>
          <p class="info-text">浏览器无法直接预览Office文档，请下载后使用Office软件打开</p>
          <div class="office-preview-options">
            <button @click="tryOfficeOnlineViewer" class="btn-office-viewer">
              尝试在线预览（需要网络）
            </button>
            <button @click="downloadFile" class="btn-download-office">
              下载文件
            </button>
          </div>
        </div>
        <iframe 
          v-if="showOfficeViewer" 
          :src="officeOnlineViewerUrl" 
          class="preview-iframe"
          frameborder="0"
        ></iframe>
      </div>
      
      <!-- 文本预览 -->
      <pre v-else-if="isText" class="preview-text">{{ textContent }}</pre>
      
      <!-- 不支持预览的格式 -->
      <div v-else class="preview-unsupported">
        <p>该文件格式不支持在线预览</p>
        <button @click="downloadFile" class="btn-download-large">下载文件</button>
      </div>
    </div>
  </div>
</template>

<script>
import { childEnglishApi } from '@/api/childEnglishApi';

export default {
  name: 'FilePreview',
  data() {
    return {
      fileName: '',
      fileExtension: '',
      previewUrl: '',
      textContent: '',
      loading: false,
      showOfficeViewer: false
    };
  },
  computed: {
    isPdf() {
      return this.fileExtension === 'pdf';
    },
    isImage() {
      return ['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(this.fileExtension);
    },
    isOfficeDoc() {
      return ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'].includes(this.fileExtension);
    },
    isText() {
      return this.fileExtension === 'txt';
    },
    officeOnlineViewerUrl() {
      // 使用Office Online Viewer预览Office文档
      // 注意：Office Online Viewer需要文件URL是公开可访问的（不能是localhost）
      // 对于本地开发环境，这个功能可能无法使用
      const baseURL = 'http://localhost:8080';
      // 使用路由参数中的编码文件名
      const encodedFileName = encodeURIComponent(this.$route.params.fileName || this.fileName);
      const fileUrl = encodeURIComponent(`${baseURL}/file/preview/${encodedFileName}`);
      // 使用Microsoft Office Online Viewer
      return `https://view.officeapps.live.com/op/embed.aspx?src=${fileUrl}`;
    }
  },
  mounted() {
    this.loadFile();
  },
  methods: {
    async loadFile() {
      const fileName = this.$route.params.fileName;
      if (!fileName) {
        this.$message?.error('文件名不存在');
        this.closePreview();
        return;
      }
      
      // 解码文件名
      const decodedFileName = decodeURIComponent(fileName);
      this.fileName = decodedFileName;
      this.fileExtension = this.getFileExtension(decodedFileName).toLowerCase();
      
      const baseURL = 'http://localhost:8080';
      // 使用原始编码的文件名构建预览URL
      this.previewUrl = `${baseURL}/file/preview/${fileName}`;
      
      console.log('预览文件:', {
        fileName: this.fileName,
        extension: this.fileExtension,
        previewUrl: this.previewUrl
      });
      
      // 如果是文本文件，加载内容
      if (this.isText) {
        await this.loadTextContent();
      }
    },
    
    async loadTextContent() {
      try {
        const response = await fetch(this.previewUrl);
        if (response.ok) {
          this.textContent = await response.text();
        }
      } catch (error) {
        console.error('加载文本内容失败:', error);
      }
    },
    
    getFileExtension(fileName) {
      const lastDot = fileName.lastIndexOf('.');
      return lastDot > 0 ? fileName.substring(lastDot + 1) : '';
    },
    
    downloadFile() {
      const baseURL = 'http://localhost:8080';
      const downloadUrl = `${baseURL}/file/download/${encodeURIComponent(this.fileName)}`;
      window.open(downloadUrl, '_blank');
    },
    
    tryOfficeOnlineViewer() {
      this.showOfficeViewer = true;
      this.$message?.info('正在加载在线预览，如果无法显示，请下载文件后使用Office软件打开');
    },
    
    closePreview() {
      // 关闭预览窗口或返回上一页
      if (window.history.length > 1) {
        this.$router.go(-1);
      } else {
        this.$router.push('/');
      }
    }
  }
};
</script>

<style scoped>
.file-preview-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.preview-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.preview-actions {
  display: flex;
  gap: 12px;
}

.btn-download,
.btn-close {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.btn-download {
  background: #1890ff;
  color: white;
}

.btn-download:hover {
  background: #40a9ff;
}

.btn-close {
  background: #f5f5f5;
  color: #333;
}

.btn-close:hover {
  background: #e8e8e8;
}

.preview-content {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 24px;
  overflow: auto;
}

.preview-iframe {
  width: 100%;
  height: 100%;
  border: none;
  background: white;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.preview-text {
  width: 100%;
  max-width: 1200px;
  height: 100%;
  padding: 24px;
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: auto;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.office-preview-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.office-preview-info {
  text-align: center;
  padding: 48px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
}

.office-preview-info p {
  margin-bottom: 16px;
  color: #333;
  font-size: 18px;
  font-weight: 500;
}

.info-text {
  color: #666;
  font-size: 14px;
  margin-bottom: 24px;
}

.office-preview-options {
  display: flex;
  gap: 16px;
  justify-content: center;
}

.btn-office-viewer,
.btn-download-office {
  padding: 12px 24px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.btn-office-viewer {
  background: #1890ff;
  color: white;
}

.btn-office-viewer:hover {
  background: #40a9ff;
}

.btn-download-office {
  background: #52c41a;
  color: white;
}

.btn-download-office:hover {
  background: #73d13d;
}

.preview-unsupported {
  text-align: center;
  padding: 48px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.preview-unsupported p {
  margin-bottom: 24px;
  color: #666;
  font-size: 16px;
}

.btn-download-large {
  padding: 12px 24px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.btn-download-large:hover {
  background: #40a9ff;
}
</style>

